﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Controls;
using System.Reflection;
using System.Windows.Input;
using System.Windows;

namespace Sparkle.Hosting
{
    public class CommandBehaviorBase<T>
        where T : Control
    {
        private ICommand command;
        private object commandParameter;
        private readonly WeakReference targetObject;
        private readonly EventHandler commandCanExecuteChangedHandler;

        private string action = string.Empty;


        /// <summary>
        /// Constructor specifying the target object.
        /// </summary>
        /// <param name="targetObject">The target object the behavior is attached to.</param>
        public CommandBehaviorBase(T targetObject)
        {
            this.targetObject = new WeakReference(targetObject);
            this.commandCanExecuteChangedHandler = new EventHandler(this.CommandCanExecuteChanged);
        }

        /// <summary>
        /// Corresponding command to be execute and monitored for <see cref="ICommand.CanExecuteChanged"/>
        /// </summary>
        public ICommand Command
        {
            get { return command; }
            set
            {
                if (this.command != null)
                {
                    this.command.CanExecuteChanged -= this.commandCanExecuteChangedHandler;
                }

                this.command = value;
                if (this.command != null)
                {
                    this.command.CanExecuteChanged += this.commandCanExecuteChangedHandler;
                    UpdateEnabledState();
                }
            }
        }

        /// <summary>
        /// The parameter to supply the command during execution
        /// </summary>
        public object CommandParameter
        {
            get { return this.commandParameter; }
            set
            {
                if (this.commandParameter != value)
                {
                    this.commandParameter = value;
                    this.UpdateEnabledState();
                }
            }
        }

        /// <summary>
        /// Object to which this behavior is attached.
        /// </summary>
        protected T TargetObject
        {
            get
            {
                return targetObject.Target as T;
            }
        }



        public string Action
        {
            get { return action; }
            set { action = value; }
        }

        /// <summary>
        /// Updates the target object's IsEnabled property based on the commands ability to execute.
        /// </summary>
        protected virtual void UpdateEnabledState()
        {
            if (TargetObject == null)
            {
                this.Command = null;
                this.CommandParameter = null;
            }
            else if (this.Command != null)
            {
                TargetObject.IsEnabled = this.Command.CanExecute(this.CommandParameter);
            }
        }

        private void CommandCanExecuteChanged(object sender, EventArgs e)
        {
            this.UpdateEnabledState();
        }

        /// <summary>
        /// Executes the command, if it's set, providing the <see cref="CommandParameter"/>
        /// </summary>
        protected virtual void ExecuteCommand()
        {
            if (this.Command != null)
            {
                this.Command.Execute(this.CommandParameter);
            }

            if (!string.IsNullOrEmpty(Action))
            {
                IViewModel controlller = getController(this.TargetObject);

                if (controlller != null)
                {
                    MethodInfo actionInfo = controlller.GetType().GetMethod(this.Action);

                    Object retObject = actionInfo.Invoke(controlller, null);

                    if (retObject != null && retObject is IActionResult)
                    {
                        (retObject as IActionResult).ExecuteResult();
                    }
                }
            }
        }

        #region private methods

        private static IViewModel getController(FrameworkElement control)
        {
            IViewModel retControlller = null;
            if (control != null && control.DataContext is IViewModel)
            {
                retControlller = control.DataContext as IViewModel;
            }
            else
            {
                if (control != null && control.Parent != null && control.Parent is FrameworkElement)
                {
                    return getController(control.Parent as FrameworkElement);//VisualTreeHelper.GetParent(control)
                }
            }

            return retControlller;
        }

        #endregion
    }

}
